package org.ilc.socketserver;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.ilc.Bootstrap;
import org.ilc.Constants;
import org.ilc.FileLogger;
import org.ilc.push.IHeader;
import org.ilc.push.IResponse;
import org.ilc.util.ValidateUtil;

import java.io.IOException;

/**
 * @author malongbo
 */
public class Response implements IResponse {
    private IoSession session;
    private Header headers;
    private byte[] body;
    private int status=200;

    public Response(IoSession session){
        this.session=session;
    }

    @Override
    public IResponse setStatus(int status) {
        this.status=status;
        return this;
    }

    @Override
    public IResponse addHeader(String name, String value) {
        if(!ValidateUtil.validateStr (name) || null == value){
            return this;
        }
        if(null == this.headers){
            this.headers = new Header();
        }
        this.headers.addHeader(name, value);
        return this;
    }

    @Override
    public IResponse setBody(byte[] body) {
        this.body=body;
        return this;
    }

    /**
     *
     * @throws java.io.IOException
     */
    @Override
    public void flush() throws IOException {
        /*
        添加头信息
         */
        int contentLength = (null == this.body) ? 0 : this.body.length;
        this.addHeader(IHeader.HEAD_STATUS_KEY, status+"");//status
        this.addHeader(IHeader.HEAD_CONTENT_LENGTH_KEY, contentLength+"");//content-length
        String headerString = this.headers.toString().concat("\r\n");

        /**
         * 将数据放入缓冲池
         */
        byte[] headerContent = headerString.getBytes(IHeader.HEADER_ENCODING_CHARSET);
        IoBuffer iobuffer = IoBuffer.allocate(headerContent.length
                + contentLength);
        iobuffer.put(headerContent);
        if(null != body){
            iobuffer.put(body);
//            System.out.println("server send data: " + new String(body) );
        }
        iobuffer.flip();


        synchronized(session){
            session.write(iobuffer);
        }

        iobuffer.free();


//        iobuffer.clear ();
        iobuffer = null;
        headerString = null;
        headerContent = null;
    }

    @Override
    public void close() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void destroy() {
        this.status=200;
        this.body=null;
        if (this.headers != null)
            this.headers.destroy();
        this.headers=null;
    }
}
